package db;

import business.GitLogic;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import pojo.GitCount;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

/**
 * @Description:
 * @Author: xiaobing
 * @system name: 工作流引擎
 * @copyright：长安新生（深圳）金融投资有限公司
 * @Date: Created in  2018/9/26 13:48
 */
public class GitCountDao {

    private static Connection conn = null;

    private static PreparedStatement pstm = null;

    private static final Logger logger = LoggerFactory.getLogger(GitCountDao.class);

    
    /**
     * @Author: xiaobing
     * @Description: git统计数据批量插入数据库
     * @Date: 2018/9/26
     */
    public static void gitCountBatchSave(String localPath, String branch,String projectCde) {
        logger.info("开始插入" + projectCde + "项目数据！");
        try {
            if(conn == null){
                conn=DBHelper.getConnection();
            }
            String sql = "INSERT INTO git_count(email_address,auth_name,commit_date,commit_message,add_line,remove_line,project_cde,is_merge) VALUES (?,?,?,?,?,?,?,?)";
            pstm = conn.prepareStatement(sql);
            conn.setAutoCommit(false);
            // 获取git统计数据
            List<GitCount> list = GitLogic.gitLogCommit(localPath,branch);
            logger.info("统计" + projectCde + "项目数据完成！正在执行数据库操作。。。。");
            // 循环批量插入数据库
            for (GitCount gitCount : list) {
                pstm.setString(1,gitCount.getEmailAddress());
                pstm.setString(2,gitCount.getAuthName());
                pstm.setString(3,gitCount.getCommitDate());
                pstm.setString(4,gitCount.getCommitMessage());
                pstm.setInt(5,gitCount.getAddLine());
                pstm.setInt(6,gitCount.getRemoveLine());
                pstm.setString(7,projectCde);
                pstm.setString(8,gitCount.getIsMerge());
                pstm.addBatch();
            }
            pstm.executeBatch();
            conn.commit();
            logger.info(projectCde + "项目数据插入完成");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(projectCde + "项目插入失败！");
        } finally {
            try {
                // 这里最好要先判断是否为空，不为空了，才去关闭。
                // 而且要从小到大的关闭，顺序不能乱
                if (pstm != null) {
                    pstm.close();
                }
                /*if (conn != null)
                    conn.close(); */    //注意：如果后续还要使用connection，则不用关闭
            } catch (SQLException e)
            {
                e.printStackTrace();
            }
        }
    }

}
